package com.example.redislock.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtils {

    private static final long TIMEOUT = 1000;
    @Resource
    private static RedisTemplate<String, Object> redisTemplate;


    /**
     * 普通加锁
     *
     * @param redisKey key
     * @param expireTime 锁过期时间
     * @return 加锁是否成功
     */
    public boolean lock(String redisKey, long expireTime) {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        long start = System.currentTimeMillis();
        // 在1s内持续拿锁，超时则返回错误
        while (true) {
            //Set命令返回OK，则证明获取锁成功
            if (Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(redisKey, requestId, expireTime, TimeUnit.SECONDS))) {
                return true;
            }
            // 否则循环等待，在timeout时间内仍未获取到锁，则获取失败
            long end = System.currentTimeMillis() - start;
            if (end >= TIMEOUT) {
                return false;
            }
        }
    }
}
